﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

using log4net;
using CashFlow.Web.App_Start;
using CashFlow.Web.Service;

namespace CashFlow.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        private static ILog _logger = LogManager.GetLogger(typeof(MvcApplication));

        protected void Application_Start()
        {
            _logger.Info("CashFlow.Web MvcApplication Startup ...");

            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            AutofacConfig.Register();
            NewtonsoftConfig.Init();
            DbConfig.Init();
        }

        protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            if (app != null && app.Context != null)
            {
                app.Context.Response.Headers.Remove("Server");
                app.Context.Response.Headers.Remove("X-AspNet-Version");
                app.Context.Response.Headers.Remove("X-AspNetMvc-Version");
            }
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            _logger.Fatal(string.Format("CashFlow.Web.Application_Error Exception: {0}", exception.Message), exception);
#if RELEASE
            Server.ClearError();
            HttpContext.Current.Response.TrySkipIisCustomErrors = true;
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.StatusCode = 500;
            HttpContext.Current.Response.Write("500");
            HttpContext.Current.Response.End();
#endif
        }
    }
}
